package cn.edu.henu.team.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.ninegrid.ImageInfo;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.io.File;
import java.util.ArrayList;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import cn.edu.henu.team.R;
import cn.edu.henu.team.bean._User;
import cn.edu.henu.team.bean.collection;
import cn.edu.henu.team.utils.myImageLoader;

public class EditCollectionActivity extends AppCompatActivity {

    private _User current_user = BmobUser.getCurrentUser(_User.class);
    private String objectId;
    private ImageView back;
    private BmobFile image_file;
    private TextView add;
    private ImageView image;
    private EditText name_edittext;
    private EditText intro_edittext;
    private String name;
    private String intro;
    private String imagePath = null;
    private ArrayList<ImageItem> imageItems;  //因为布局不熟，目前先是一张图片吧

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_collection);

        Intent it = getIntent();
        objectId = it.getStringExtra("objectId");

        findView();
        clickEvents();

    }

    public void findView() {
        back =  findViewById(R.id.back);
        add = findViewById(R.id.add);
        image =  findViewById(R.id.image);
        name_edittext =  findViewById(R.id.name);
        intro_edittext =  findViewById(R.id.introduction);

        BmobQuery<collection> query2 = new BmobQuery<collection>();
        query2.getObject(objectId, new QueryListener<collection>() {
            @Override
            public void done(collection object, BmobException e) {
                if(e==null){
                    name_edittext.setText(object.getName().toString());
                    intro_edittext.setText(object.getIntroduction().toString());
                    ImageLoader.getInstance().displayImage(object.getImage().getFileUrl(), image);
                }else{
                    Toast.makeText(getApplicationContext(), "收藏夹查询失败", Toast.LENGTH_SHORT).show();
                }
            }

        });
    }

    public void clickEvents() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name = name_edittext.getText().toString();
                intro = intro_edittext.getText().toString();
                if (name.equals("") && intro.equals("") && imagePath == null)
                    finish();
                else {
                    createDialog();
                }
            }
        });

        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开相册进行选择
               addImage(1);
            }
        });

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name = name_edittext.getText().toString();
                intro = intro_edittext.getText().toString();
                if (name.equals(""))
                    Toast.makeText(getApplicationContext(), "收藏夹标题不能为空哦", Toast.LENGTH_SHORT).show();
                else
                    uploadImage_then_create();//发表帖子
            }
        });
    }



    /**
     * 将图片上传到 Bmob然后创建新收藏夹
     */
    public void uploadImage_then_create() {
        name = name_edittext.getText().toString();
        intro = intro_edittext.getText().toString();
        // 查看需不需要上传图片
        if (imagePath != null) {
            image_file = new BmobFile(new File(imagePath));
            //要先上传图片，之后才能将图片加载到新建数据列里
            image_file.uploadblock(new UploadFileListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        collection c = new collection();
                        c.setImage(image_file);
                        c.setName(name);
                        c.setIntroduction(intro);
                        c.update(objectId, new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if(e==null){
                                    Toast.makeText(getApplicationContext(), "更改成功", Toast.LENGTH_SHORT).show();
                                    Intent i = new Intent();
                                    setResult(0, i);
                                    finish();
                                    //overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
                                }else{
                                    Toast.makeText(getApplicationContext(), "更改失败", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    } else {
                        Toast.makeText(getApplication(), "更改失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            collection c = new collection();
            c.setName(name);
            c.setIntroduction(intro);
            c.update(objectId, new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if(e==null){
                        Toast.makeText(getApplicationContext(), "更改成功", Toast.LENGTH_SHORT).show();
                        finish();
                        //overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
                    }else{
                        Toast.makeText(getApplicationContext(), "更改失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    public void createDialog() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setMessage("内容无法保存，确定离开？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                }).create();
        alertDialog.show();
    }

    /*
     *访问相册上传照片
     */
    private void addImage(Integer imageNum) {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new myImageLoader());
        imagePicker.setMultiMode(false);   //多选
        imagePicker.setSelectLimit(imageNum);    //最多选择X张
        imagePicker.setCrop(true);       //不进行裁剪
        Intent intent = new Intent(EditCollectionActivity.this, ImageGridActivity.class);
        startActivityForResult(intent, 100);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 100) {
                ArrayList<ImageInfo> imageInfo = new ArrayList<>();
                imageItems = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String[] filePaths = new String[imageItems.size()];
                filePaths[0] = imageItems.get(0).path;
                imagePath = filePaths[0];
                Log.d("path",imagePath);
            }else {
                Toast.makeText(getApplicationContext(), "没有选择图片呢", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
